"""
页面检测器

用于识别和判断页面类型
"""

import asyncio
import sys
from typing import Dict, Any, Optional, List
from playwright.async_api import Page
from pathlib import Path

# 添加项目根目录到Python路径
project_root = Path(__file__).parent.parent.parent.parent
sys.path.insert(0, str(project_root))

try:
    from src.browser.page_handler import BasePageHandler
    from src.utils.logger import get_logger
except ImportError:
    try:
        from ..page_handler import BasePageHandler
        from utils.logger import get_logger
    except ImportError:
        from browser.page_handler import BasePageHandler
        from utils.logger import get_logger

logger = get_logger(__name__)


class PageDetector(BasePageHandler):
    """页面检测器类"""
    
    def __init__(self, page: Page):
        super().__init__(page)
        self.page_patterns = {
            'game_page_a': {
                'indicators': [
                    'button:has-text("立即下载")',
                    'a:has-text("立即下载")',
                    '.download-btn',
                    '.game-download',
                    '#download-button'
                ],
                'title_keywords': ['游戏', 'game', '下载', 'download'],
                'url_patterns': ['/game/', '/download/', '/play/']
            },
            'game_page_b': {
                'indicators': [
                    'button:has-text("开始游戏")',
                    'button:has-text("进入游戏")',
                    '.play-btn',
                    '.start-game',
                    '#play-button'
                ],
                'title_keywords': ['游戏', 'game', '开始', 'play'],
                'url_patterns': ['/play/', '/start/', '/game/']
            },
            'password_protected_page': {
                'indicators': [
                    'h1:has-text("密码保护")',
                    'h1.entry-title:has-text("密码保护")',
                    '.entry-title:has-text("密码保护")',
                    'input[name="post_password"]',
                    'input[type="password"]',
                    '#pwbox-30110'
                ],
                'title_keywords': ['密码保护', 'password', '密码', 'protected'],
                'url_patterns': ['/password/', '/protected/']
            },
            'download_dialog': {
                'indicators': [
                    '.download-dialog',
                    '.modal:has-text("下载")',
                    '.popup:has-text("下载")',
                    'dialog[open]',
                    '.download-modal'
                ],
                'title_keywords': ['下载', 'download'],
                'url_patterns': []
            },
            'password_page': {
                'indicators': [
                    'input[type="password"]',
                    '.password-input',
                    'form:has-text("密码")',
                    'input:has-text("密码")',
                    '.auth-form'
                ],
                'title_keywords': ['密码', 'password', '验证', 'auth'],
                'url_patterns': ['/auth/', '/login/', '/password/']
            },
            'baidu_netdisk': {
                'indicators': [
                    '.share-link',
                    '.extract-code',
                    'a[href*="pan.baidu.com"]',
                    '.netdisk-link',
                    'text="提取码"'
                ],
                'title_keywords': ['百度网盘', 'baidu', 'netdisk', '提取码'],
                'url_patterns': ['pan.baidu.com']
            }
        }
    
    async def handle(self) -> Dict[str, Any]:
        """
        检测页面类型
        
        Returns:
            Dict: 页面检测结果
        """
        try:
            # 等待页面加载
            await self.wait_for_page_load()
            
            # 获取页面基本信息
            page_info = await self.get_page_info()
            
            # 检测页面类型
            page_type = await self.detect_page_type()
            
            # 检测页面加载状态
            load_status = await self.check_page_load_status()
            
            # 检测弹窗
            popups = await self.check_for_popups()
            
            result = {
                'page_type': page_type,
                'page_info': page_info,
                'load_status': load_status,
                'popups': popups,
                'has_popups': len(popups) > 0,
                'detection_time': asyncio.get_event_loop().time()
            }
            
            self.logger.info(f"页面检测完成: {page_type}")
            return result
            
        except Exception as e:
            self.logger.error(f"页面检测失败: {str(e)}")
            return {
                'page_type': 'unknown',
                'error': str(e),
                'detection_time': asyncio.get_event_loop().time()
            }
    
    async def detect_page_type(self) -> str:
        """
        检测页面类型
        
        Returns:
            str: 页面类型
        """
        try:
            page_url = self.page.url.lower()
            page_title = (await self.page.title()).lower()
            
            # 按优先级检测页面类型
            for page_type, patterns in self.page_patterns.items():
                score = 0
                
                # 检查URL模式
                for url_pattern in patterns['url_patterns']:
                    if url_pattern in page_url:
                        score += 3
                        self.logger.debug(f"URL匹配: {url_pattern} -> {page_type}")
                
                # 检查标题关键词
                for keyword in patterns['title_keywords']:
                    if keyword in page_title:
                        score += 2
                        self.logger.debug(f"标题匹配: {keyword} -> {page_type}")
                
                # 检查页面元素指示器
                for indicator in patterns['indicators']:
                    try:
                        element = await self.page.query_selector(indicator)
                        if element and await element.is_visible():
                            score += 5
                            self.logger.debug(f"元素匹配: {indicator} -> {page_type}")
                    except Exception as e:
                        self.logger.debug(f"检查元素 {indicator} 失败: {str(e)}")
                
                # 如果得分足够高，认为匹配
                if score >= 5:
                    self.logger.info(f"检测到页面类型: {page_type} (得分: {score})")
                    return page_type
            
            # 如果没有匹配的类型，返回unknown
            self.logger.warning("无法确定页面类型")
            return 'unknown'
            
        except Exception as e:
            self.logger.error(f"页面类型检测失败: {str(e)}")
            return 'error'
    
    async def check_page_load_status(self) -> Dict[str, Any]:
        """
        检查页面加载状态
        
        Returns:
            Dict: 加载状态信息
        """
        try:
            # 检查页面加载状态
            load_state = await self.page.evaluate("""
                () => {
                    return {
                        readyState: document.readyState,
                        hasImages: document.images.length > 0,
                        hasScripts: document.scripts.length > 0,
                        hasStylesheets: document.styleSheets.length > 0,
                        bodyLoaded: !!document.body,
                        imagesLoaded: Array.from(document.images).every(img => img.complete)
                    };
                }
            """)
            
            # 检查网络活动
            network_idle = True
            try:
                await self.page.wait_for_load_state("networkidle", timeout=3000)
            except:
                network_idle = False
            
            # 检查关键元素是否存在
            key_elements = await self.page.evaluate("""
                () => {
                    const selectors = ['button', 'a', 'input', 'form'];
                    const counts = {};
                    selectors.forEach(sel => {
                        counts[sel] = document.querySelectorAll(sel).length;
                    });
                    return counts;
                }
            """)
            
            status = {
                'ready_state': load_state['readyState'],
                'network_idle': network_idle,
                'has_images': load_state['hasImages'],
                'has_scripts': load_state['hasScripts'],
                'has_stylesheets': load_state['hasStylesheets'],
                'body_loaded': load_state['bodyLoaded'],
                'images_loaded': load_state['imagesLoaded'],
                'key_elements': key_elements,
                'is_fully_loaded': (
                    load_state['readyState'] == 'complete' and
                    load_state['bodyLoaded'] and
                    network_idle
                )
            }
            
            self.logger.debug(f"页面加载状态: {status}")
            return status
            
        except Exception as e:
            self.logger.error(f"检查页面加载状态失败: {str(e)}")
            return {'error': str(e), 'is_fully_loaded': False}
    
    async def find_download_button(self) -> Optional[Dict[str, Any]]:
        """
        查找下载按钮
        
        Returns:
            Dict: 下载按钮信息
        """
        try:
            download_selectors = [
                'button:has-text("立即下载")',
                'a:has-text("立即下载")',
                'button:has-text("下载")',
                'a:has-text("下载")',
                '.download-btn',
                '.download-button',
                '#download',
                '#download-btn',
                '.btn-download',
                '[data-action="download"]',
                'button[onclick*="download"]',
                'a[href*="download"]'
            ]
            
            for selector in download_selectors:
                try:
                    element = await self.page.query_selector(selector)
                    if element and await element.is_visible():
                        # 获取按钮信息
                        button_info = {
                            'selector': selector,
                            'text': await element.text_content(),
                            'href': await element.get_attribute('href'),
                            'onclick': await element.get_attribute('onclick'),
                            'position': await element.bounding_box(),
                            'element': element
                        }
                        
                        self.logger.info(f"找到下载按钮: {selector}")
                        return button_info
                        
                except Exception as e:
                    self.logger.debug(f"检查下载按钮 {selector} 失败: {str(e)}")
            
            self.logger.warning("未找到下载按钮")
            return None
            
        except Exception as e:
            self.logger.error(f"查找下载按钮失败: {str(e)}")
            return None
    
    async def is_download_dialog_open(self) -> bool:
        """
        检查下载对话框是否打开
        
        Returns:
            bool: 是否有下载对话框
        """
        try:
            dialog_selectors = [
                '.download-dialog',
                '.modal:has-text("下载")',
                '.popup:has-text("下载")',
                'dialog[open]',
                '.download-modal',
                '.save-dialog',
                '[role="dialog"]:has-text("下载")'
            ]
            
            for selector in dialog_selectors:
                try:
                    element = await self.page.query_selector(selector)
                    if element and await element.is_visible():
                        self.logger.info(f"检测到下载对话框: {selector}")
                        return True
                except Exception as e:
                    self.logger.debug(f"检查对话框 {selector} 失败: {str(e)}")
            
            return False
            
        except Exception as e:
            self.logger.error(f"检查下载对话框失败: {str(e)}")
            return False
    
    async def get_page_elements_summary(self) -> Dict[str, Any]:
        """
        获取页面元素摘要
        
        Returns:
            Dict: 页面元素统计信息
        """
        try:
            summary = await self.page.evaluate("""
                () => {
                    return {
                        buttons: document.querySelectorAll('button').length,
                        links: document.querySelectorAll('a').length,
                        inputs: document.querySelectorAll('input').length,
                        forms: document.querySelectorAll('form').length,
                        images: document.querySelectorAll('img').length,
                        videos: document.querySelectorAll('video').length,
                        iframes: document.querySelectorAll('iframe').length,
                        modals: document.querySelectorAll('.modal, .popup, dialog').length,
                        downloadElements: document.querySelectorAll('[href*="download"], [onclick*="download"], .download').length
                    };
                }
            """)
            
            return summary
            
        except Exception as e:
            self.logger.error(f"获取页面元素摘要失败: {str(e)}")
            return {}